package com.example.hyg_veintype.activity.account.register;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.core.content.ContextCompat;

import com.example.hyg_veintype.R;
import com.example.hyg_veintype.activity.MainActivity;
import com.example.hyg_veintype.activity.account.login.LoginActivity;
import com.example.hyg_veintype.activity.web.WebViewActivity;
import com.example.hyg_veintype.base.BaseHandler;
import com.example.hyg_veintype.base.BaseVeinTypeActivity;
import com.example.hyg_veintype.base.api.ApiServiceManager;
import com.example.hyg_veintype.base.api.IGsonResponse;
import com.example.hyg_veintype.constant.account.AccountConst;
import com.example.hyg_veintype.data.net.passwordReset.PassWordResetWraper;
import com.example.hyg_veintype.data.net.register.RegisterWraper;
import com.example.hyg_veintype.data.net.smscodeGet.SmsCodeGetWraper;
import com.example.hyg_veintype.utils.AppManager;
import com.hyg.lib_base.mainUtils.ToastUtils;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;



import okhttp3.FormBody;

import static com.hyg.lib_common.constant.UrlUtils.PrivacyUrl;
import static com.hyg.lib_common.constant.UrlUtils.codeaddr;
import static com.hyg.lib_common.constant.UrlUtils.regisiterAddr;
import static com.hyg.lib_common.constant.UrlUtils.resetAddr;

/**
 * @author: yyw
 * time: 2020/12/22 10:22
 * desc:注册及忘记密码页面
 */
public class RegisterActivity extends BaseVeinTypeActivity implements BaseHandler.OnReceiveMessageListener{

    public String mphone = "[1][345789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个

    EditText etPhone;
    Button getcode;
    EditText etCode;
    EditText etPassword;
    ToggleButton togglePwd;
    Button btRegister;
    CheckBox CBAgreement;
    TextView Agreement;
    LinearLayout lnBottom;

    public static final int INDEX_REGISTER = 1;//注册
    public static final int INDEX_FORGET = 2;//忘记密码
    static int jumpType = 1;
    private static final int MSG_SENDPIN = 1001;//发送验证码
    private static final int MSG_AUTOLOGIN = 1002;//自动登录
    private static final int COUNT_SECOND = 60;
    private static final int COUNT_AUTOLOGIN = 3;
    private static int msgIndex = COUNT_SECOND;
    private static int autoLoginIndex = COUNT_AUTOLOGIN;
    SweetAlertDialog dialog;
    BaseHandler baseHandler;
    TextView timertext;

    @Override
    public void handlerMessage(Message msg) {
        switch (msg.what) {
            case MSG_SENDPIN:
                if (msgIndex > 0) {
                    msgIndex--;
                    getcode.setText(msgIndex + "s后可获取");
                    getcode.setEnabled(false);
                    getcode.setAlpha(0.5f);
                    baseHandler.sendEmptyMessageDelayed(MSG_SENDPIN, 1000);
                } else {//60秒后可再发送
                    msgIndex = COUNT_SECOND;
                    getcode.setEnabled(true);
                    getcode.setText("获取验证码");
                    getcode.setAlpha(0.9f);
                }
                break;
            case MSG_AUTOLOGIN:
                if (autoLoginIndex > 0) {
                    autoLoginIndex--;
                    timertext.setText(autoLoginIndex + "");
                    baseHandler.sendEmptyMessageDelayed(MSG_AUTOLOGIN, 1000);
                } else {//60秒后可再发送
                    autoLoginIndex = COUNT_AUTOLOGIN;
                    jumpActivity();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 注册页及忘记密码页面入口
     *
     * @param context
     * @param index   INDEX_REGISTER(1注册)，INDEX_FORGET（2忘记密码）
     */
    public static void start(Context context, int index) {
        jumpType = index;
        Intent starter = new Intent(context, RegisterActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.veintype_activity_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvTitle.setTextColor(ContextCompat.getColor(this, R.color.MainThemeColor));
        if (jumpType == INDEX_REGISTER) {
            tvTitle.setText("注册");
            btRegister.setText("注册");
        } else if (jumpType == INDEX_FORGET) {
            tvTitle.setText("忘记密码");
            btRegister.setText("修改密码");
            lnBottom.setVisibility(View.GONE);
        }


        etPhone = findViewById(R.id.et_phone);
        getcode = findViewById(R.id.getcode);
        getcode.setOnClickListener(this);
        etCode = findViewById(R.id.et_code);
        etPassword = findViewById(R.id.et_password);
        togglePwd = findViewById(R.id.togglePwd);
        togglePwd.setOnClickListener(this);
        btRegister = findViewById(R.id.bt_register);
        btRegister.setOnClickListener(this);
        CBAgreement = findViewById(R.id.CB_Agreement);
        CBAgreement.setOnClickListener(this);
        Agreement = findViewById(R.id.Agreement);
        Agreement.setOnClickListener(this);
        lnBottom = findViewById(R.id.ln_bottom);


        baseHandler = new BaseHandler(this);
        dialog = new SweetAlertDialog(this);
        Agreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
    }


    @Override
    public void onClick(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        int id = view.getId();
        if (id == R.id.getcode) {
            doSendSMSCode(etPhone.getText().toString());
        } else if (id == R.id.togglePwd) {
            if (togglePwd.isChecked()) {
                //显示密码
                etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //隐藏密码
                etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        } else if (id == R.id.bt_register) {
            if (jumpType == INDEX_REGISTER) {
                doRegister(etPhone.getText().toString(), etCode.getText().toString(), etPassword.getText().toString());
            } else if (jumpType == INDEX_FORGET) {
                doResetPassWord(etPhone.getText().toString(), etCode.getText().toString(), etPassword.getText().toString());
            }
        } else if (id == R.id.CB_Agreement) {
            showAgreementDialog();
        } else if (id == R.id.Agreement) {
            WebViewActivity.start(this, PrivacyUrl, "隐私政策与免责声明", "Privacy");
        }
    }

    /**
     * 显示自动登录对话框
     */
    private void showAutoLoginDialog() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_layouts, null);
        timertext = view.findViewById(R.id.tv_dialog);
        timertext.setGravity(Gravity.CENTER);
        timertext.setText(autoLoginIndex + "");
        dialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
        dialog.setTitleText("注册成功，即将帮您自动登录");
        dialog.setCustomView(view);
        dialog.setConfirmButton("直接登录", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                baseHandler.removeCallbacksAndMessages(null);
                jumpActivity();
            }
        });
        dialog.show();
        baseHandler.sendEmptyMessageDelayed(MSG_AUTOLOGIN, 1500);
    }

    /**
     * 错误提示对话框
     *
     * @param title
     * @param contentMsg
     */
    private void showErrorDialog(String title, String contentMsg) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new SweetAlertDialog(this);
        dialog.changeAlertType(SweetAlertDialog.ERROR_TYPE)
                .setTitleText(title)
                .setContentText(contentMsg)
                .setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                }).show();
    }

    /**
     * 成功对话框
     *
     * @param title
     * @param contentMsg
     * @param btStr
     * @param onSweetClickListener
     */
    private void showSuccessDialog(String title, String contentMsg, String btStr, SweetAlertDialog.OnSweetClickListener onSweetClickListener) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new SweetAlertDialog(this);
        dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText(title)
                .setContentText(contentMsg)
                .setConfirmButton(btStr, onSweetClickListener)
                .show();
    }

    /************** 注册成功页面跳转 **************/
    private void jumpActivity() {
        dialog.dismiss();
        AppManager.getAppManager().finishAllActivity();
        MainActivity.start(RegisterActivity.this);
    }

    /**
     * 注册
     */
    private void doRegister(String phone, String code, String pass) {
        if (TextUtils.isEmpty(phone)) {
            showErrorDialog("格式错误", "请填写手机号");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showErrorDialog("格式错误", "请填写验证码");
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            showErrorDialog("格式错误", "请填写密码");
            return;
        }
        if (!CBAgreement.isChecked()) {
            showErrorDialog("《隐私政策与免责声明》错误", "请阅读并勾选《隐私政策与免责声明》");
            return;
        }
        if (!phone.matches(mphone)) {
            showErrorDialog("格式错误", "手机号格式错误，请重新输入");
            return;
        }
        if (!code.matches(mcode)) {
            showErrorDialog("格式错误", "验证码格式错误，请重新输入。");
            return;
        }
        if (!pass.matches(mpassword)) {
            showErrorDialog("格式错误", "密码格式不对或者包含非格式字符，请重新输入。");
            return;
        }
        progressDialog.show();
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .add("password", pass)
                .add("smsCode", code)
                .build();
        ApiServiceManager.getInstance().postRequest(regisiterAddr, formBody, RegisterWraper.class, new IGsonResponse<RegisterWraper>() {
            @Override
            public void onSuccess(RegisterWraper model, String response) {
                progressDialog.dismiss();
                if (model.getCode() == 200) {
                    AccountConst.saveAccountData(RegisterActivity.this,
                            phone,
                            pass,
                            model.getData().getToken());
                    showAutoLoginDialog();
                } else {
                    showErrorDialog("注册失败", TextUtils.isEmpty(model.getMessage()) ? "未知错误" : model.getMessage());
                }
            }

            @Override
            public void onError(String msg) {
                progressDialog.dismiss();
                showErrorDialog("注册失败", "服务器错误");
            }
        });
    }

    private void doResetPassWord(String phone, String code, String pass) {
        if (TextUtils.isEmpty(phone)) {
            showErrorDialog("格式错误", "请填写手机号");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showErrorDialog("格式错误", "请填写验证码");
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            showErrorDialog("格式错误", "请填写密码");
            return;
        }
        if (!phone.matches(mphone)) {
            showErrorDialog("格式错误", "手机号格式错误，请重新输入");
            return;
        }
        if (!code.matches(mcode)) {
            showErrorDialog("格式错误", "验证码格式错误，请重新输入。");
            return;
        }
        if (!pass.matches(mpassword)) {
            showErrorDialog("格式错误", "密码格式不对或者包含非格式字符，请重新输入。");
            return;
        }
        progressDialog.show();
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .add("newPassword", pass)
                .add("smsCode", code)
                .build();
        ApiServiceManager.getInstance().postRequest(resetAddr, formBody, PassWordResetWraper.class, new IGsonResponse<PassWordResetWraper>() {
            @Override
            public void onSuccess(PassWordResetWraper model, String response) {
                progressDialog.dismiss();
                if (model.getCode() == 200) {
                    showSuccessDialog("密码修改成功", "", "点我去登录", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            AppManager.getAppManager().finishAllActivity();
                            LoginActivity.start(RegisterActivity.this);
                        }
                    });
                } else {
                    showErrorDialog("修改密码失败", TextUtils.isEmpty(model.getMessage()) ? "未知错误" : model.getMessage());
                }
            }

            @Override
            public void onError(String msg) {
                progressDialog.dismiss();
                showErrorDialog("修改密码失败", "服务器错误");
            }
        });
    }

    /**
     * 发送验证码
     *
     * @param phone 手机号
     */
    private void doSendSMSCode(String phone) {

        if (TextUtils.isEmpty(phone)) {
            showErrorDialog("格式错误", "请填写手机号");
            return;
        }
        if (!phone.matches(mphone)) {
            showErrorDialog("格式错误", "手机号格式错误，请重新输入");
            return;
        }
        etCode.setHint("请注意查看短信");
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .build();
        ApiServiceManager.getInstance().postRequest(codeaddr, formBody, SmsCodeGetWraper.class, new IGsonResponse<SmsCodeGetWraper>() {
            @Override
            public void onSuccess(SmsCodeGetWraper model, String response) {
                progressDialog.dismiss();
                if (model.getCode() == 200) {
                    getcode.setEnabled(false);
                    baseHandler.sendEmptyMessageDelayed(MSG_SENDPIN, 1000);
                    if (!TextUtils.isEmpty(model.getMessage())) {
                        ToastUtils.showShort(model.getMessage());
                    }
                } else {
                    showErrorDialog("获取短信失败", TextUtils.isEmpty(model.getMessage()) ? "未知错误" : model.getMessage());
                }
            }

            @Override
            public void onError(String msg) {
                progressDialog.dismiss();
                showErrorDialog("获取短信失败", "网络错误");
            }
        });
    }


    /**
     * 隐私政策对话框
     */
    private void showAgreementDialog() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new SweetAlertDialog(this);
        dialog.setTitleText("提示")
                .setContentText("注册账号须请您接受\n《隐私政策和免责声明》")
                .changeAlertType(SweetAlertDialog.WARNING_TYPE)
                .setConfirmButton("我同意", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        CBAgreement.setChecked(true);
                    }
                })
                .show();
    }

}
